﻿using DigDes.DSchool.SUPS.DataAccess.Interface;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Security.Permissions;

namespace DigDes.DSchool.SUPS.DataAccess.FileLoaders
{
    public class MyLoader1 : ILoader<MyLoader1DTO>
    {
        // TODO: Реализовать интерфейс загрузчика и логику проверки типа файла/лоигку загрузки файла

        public bool Check(string filePath)
        {
            if (System.IO.File.Exists(filePath))
            {
               
                if (Path.GetExtension(filePath).Equals((string)".OUT"))
                {
                    try
                    {
                        StreamReader sr = new StreamReader(filePath);
                        try
                        {
                            if (sr.ReadLine().Length == 70 || sr.ReadLine().Length == 116) return true;
                        }
                        catch (Exception ex)
                        {
                            return false;
                        }
                        sr.Close();
                    }
                    catch (Exception ex)
                    {
                        return false;
                    }
                }
                
            }
            return false;
        }

        public IEnumerable<MyLoader1DTO> Load(string filePath)
        {
            StreamReader sr = new StreamReader(filePath);
            string buf;
            
            while(!sr.EndOfStream)
            {
                var row = new MyLoader1DTO();
                buf=sr.ReadLine();
                if (buf.Length == 70)
                {
                    row.InventoryCarriageNumber = buf.Substring(0, 8);
                    row.WeightTons = buf.Substring(8, 3);
                    row.DestinationStation = buf.Substring(11, 5);
                    row.CargoCodeTariff =buf.Substring(16, 5);
                    row.ConsigneeCode = buf.Substring(21, 4);
                    row.ParkType = buf.Substring(25, 2);
                    row.StartStation = buf.Substring(27, 5);
                    row.OperationCode = buf.Substring(32, 2);
                    row.OperationDate = buf.Substring(34, 4);
                    row.OperationYear = buf.Substring(38, 2);
                    row.OperationTime = buf.Substring(40, 4);
                    row.StationOfOperation = buf.Substring(44, 5);
                    row.DeliveryRoad =buf.Substring(49, 2);
                    row.ReceiptRoad = buf.Substring(51, 2);
                    row.TrainIndex = buf.Substring(53, 13);
                    row.TrainNumber = buf.Substring(66, 4);
                }
                yield return row;
            }

            sr.Close();
        }
    }
}
